// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()

  if (event.action && usersHelper[event.action]) {
    const result = await usersHelper[event.action](wxContext, event)
    return result
  }

  return {
    message: 'This action was not found',
    error: -1,
  }
}

//数据库
const db = cloud.database()
const users = db.collection("users")

const usersHelper = {
  async addUser(context, params) {
    return await users.add({
      data: {
        date: db.serverDate(),
        userInfo: params.data,
        _openid:context.OPENID
      }
    })
  },
  async getUserInfo(context, params) {
    return await users.where({
      _openid: context.OPENID
    }).get()
  }
}